/***
 * @Author:xxx
 * @Date:2020-08-08 22:04:07
 * @LastModifiedBy:xxx
 * @Last Modified time:2020-08-10 15:24:38
 */

import React , { Component } from 'react';
import './user-mgt.css';
import { Input, Table, Modal,Select, message,Tag} from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import LinkButton from '../../components/link-button/linkButton.jsx';
import { reqOrgSearch,reqNameSearch,reqMobileSearch,reqEditUserInfor,reqDeleteUser,reqLockedConfirm,reqEnableConfirm,
  reqOrganListByParentOrgid1} from '../../api';
import EditUserForm from '../../components/Modal/edit-user-form';
import {connect} from 'react-redux';
import {getRolesButtons} from '../../utils/storageUtils';
import editIcon from '../../assets/image/edit.png'
import deleteIcon from '../../assets/image/delete.png'
const { Search } = Input;
const { confirm } = Modal;
const { Option } = Select;
const userList1 = [{
  user_mobile: '17726354839',
  user_name: '郭德纲',
  user_email: '15623@qq.com',
  user_enable:true,
  user_locked:false,
  user_remark:'111',
  org:{
    org_id:"org1",
    org_name:'组织1',
    org_pid:'111'
  },
  ws:{
    ws_id:'ws1',
    ws_name:'工区1',
  },
  user_roles:[{
    role_id:'r1',
    role_name:'r1',
    role_name_Zh:'r1管理员',
    role_remark:'r1管理员',
    role_menus:[{
      title:"用户管理",
      objectid:"11",
      key:"/user-mgt",
      button:[{
        lable:"编辑",
        value:"user-edit",
        objectid:"",
        pid:""
      }]
    }]
  }]
},{
  user_mobile: '177263544449',
  user_name: '郭麒麟',
  user_email: '15623@qq.com',
  user_enable:false,
  user_locked:false,
  user_remark:'111',
  org:{
    org_id:"org1",
    org_name:'组织1',
    org_pid:'111'
  },
  ws:{
    ws_id:'ws1',
    ws_name:'工区1',
  },
  user_roles:[{
    role_id:'r1',
    role_name:'r1',
    role_name_Zh:'r1管理员',
    role_remark:'r1管理员',
    role_menus:[{
      title:"用户管理",
      objectid:"11",
      key:"/user-mgt",
      button:[{
        lable:"编辑",
        value:"user-edit",
        objectid:"",
        pid:""
      }]
    }]
  },{
    role_id:'r2',
    role_name:'r2',
    role_name_Zh:'r2管理员',
    role_remark:'r2管理员',
    role_menus:[{
      title:"用户管理",
      objectid:"22",
      key:"/user-mgt",
      button:[{
        lable:"编辑",
        value:"user-edit",
        objectid:"",
        pid:""
      }]
    }]
  }]
}]

class UserMgt extends Component {   

  state = {
    userList:[],
    dataSource:[],
    roleList:[],   // 显示所有角色的列表
    user_roles:[],
    roleButtons:[], // 有权限的按钮
    visible: '0',
    loading: false,
    organList:[],
    searchType:'org_search'
  }; 

  formRef = React.createRef();

  handleSearchType = (e) => {  // 修改查找类型
    this.setState({
      searchType:e
    })
  }
  showSearchByType = (searchType) => {  // 根据查找类型显示不同的搜索框
    if(searchType === 'name_search'){
      return (
        <Search
          className='user-header-search'
          placeholder="根据用户名称搜索"
          enterButton="搜索"
          size="middle"
          onSearch={(value) => this.handleNameSearch(value)}
          loading={this.state.loading}
        />
      )
    }else if(searchType === 'mobile_search'){
      return (
        <Search
          className='user-header-search'
          placeholder="根据手机号码搜索"
          enterButton="搜索"
          size="middle"
          onSearch={(value) => this.handleMobileSearch(value)}
          loading={this.state.loading}
        />
      )
    }else {
      return (
        <Select
            className='user-header-dropdown'
            style={{ width: 170 }} 
            showSearch
            placeholder="请选择矿区"
            onChange={(e) => this.getUserList(e)}  // 返回选中项的value值 
            dropdownStyle={{
              background:'rgb(7,20,75)',
              border:'1px solid rgb(24 53 142)'
            }}
          >
            {this.state.organList.map((item) => <Option style={{color:'rgb(165,173,180)'}} value={item.org_id}>{item.org_name}</Option>)}
          </Select>
      )
    }  
  }

  handleNameSearch = async(value) => {   // 按姓名查找
    const org_id = this.props.user.org.org_id;
    const user_name = value;
    const result = await reqNameSearch(user_name,org_id);
    // console.log("姓名查找用户",result)
    if(result.code === 200){
      const userList = result.data;
      userList.map((item,index) => {   
        userList[index]['org_name'] = item.org.org_name;
      })
      this.setState({
        userList
      })
    }else{
      message.error(result.data);
    }
  };

  handleMobileSearch = async(value) => {   // 按手机号查找
    const org_id = this.props.user.org.org_id;
    const user_mobile = value;
    const result = await reqMobileSearch(user_mobile,org_id);
    console.log("手机号查找用户",result)
    if(result.code === 200){
      var userList = result.data;
      userList.map((item,index) => {   
        userList[index]['org_name'] = item.org.org_name;
      })
      this.setState({
        userList
      })
    }else{
      message.error(result.data);
    }  
  };

  initColumns = () => {      //初始化 表格的 列  vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
    this.columns = [
      { title: '姓名', dataIndex: 'user_name', key: 'user_name', 
        sorter: {
          compare: (a,b)=>a.user_name.localeCompare(b.user_name),   //中文排序参照函数 String.prototype.localeCompare()
        },
      },
      { title: '所属矿区', dataIndex: 'org_name', key: 'org_name', },
      { title: '电话', dataIndex: 'user_mobile', key: 'user_mobile', },
      { title: '邮箱', dataIndex: 'user_email', key: 'user_email', },
      { 
        title: '角色', 
        dataIndex: '', 
        key: 'user_roles',
        
        render: (tags) => (
          tags.user_roles.map(item => {
            return (
              <Tag key={item.role_id} color='rgb(61 63 199)' style={{color:'rgb(165,173,180)'}}>
                {item.role_name_Zh}
              </Tag>
            );
          })
        ),
      },
      { title: '备注', dataIndex: 'user_remark', key: 'user_remark',},
      {
        title: '操作',
        dataIndex: '',
        key: 'action',
        width: 350,
        render: (userInfor) => (
        <span>
          <LinkButton onClick={ this.state.roleButtons.indexOf("user-edit") === -1 ? this.noRightMessage : () => this.editShow(userInfor)} >
          <img src={editIcon} alt="" />
          </LinkButton>
          <LinkButton onClick={ this.state.roleButtons.indexOf("user-delete") === -1 ? this.noRightMessage : () => this.showDeleteConfirm(userInfor)}>
          <img src={deleteIcon} alt="" />
          </LinkButton>
          <LinkButton onClick={ this.state.roleButtons.indexOf("user-locked") === -1 ? this.noRightMessage : () => this.showLockedConfirm(userInfor)}>{(userInfor.user_locked)?<div className='lookBtn'>解锁</div>:<div className='lookBtn' style={{color: 'grey'}}>锁定</div>}</LinkButton>
          <LinkButton onClick={ this.state.roleButtons.indexOf("user-enabled") === -1 ? this.noRightMessage : () => this.showEnableConfirm(userInfor)}>{(userInfor.user_enable)?<div className='lookBtn' style={{color: 'grey'}}>停用</div>:<div className='lookBtn'>启用</div>}</LinkButton>  
        </span>
        ),  
      },
    ];
  };
 

  getUserList = async(e) => {  // 组织id获取用户信息列表数据 
    var org_id;
    if(e){
      org_id = e
    }else{
      org_id = this.props.user.org.org_id
    }
    this.setState({loading: true});
    const result = await reqOrgSearch(org_id);
    console.log("组织id获取全部用户",result); 
    this.setState({loading: false})
    if(result.code === 200){
      const userList = result.data; 
      userList.map((item,index) => {   
        userList[index]['org_name'] = item.org.org_name;
      })
      this.setState({
        userList
      })
    };       
  };

  getOrganList = async() => {  // 获取用户权限内的全部组织
    const org_pid = this.props.user.org.org_id;
    this.setState({ loading: true })
    const result = await reqOrganListByParentOrgid1(org_pid);
    this.setState({loading: false});
    const organList = result.data;  
    this.setState({
      organList
    })
  }

  getroleButtons = () => {  // 获取该模块的有权限的按钮
    getRolesButtons().map((item) => {
      if(item.key === '/user-mgt'){
        this.setState({
          roleButtons: item.buttons   
        })
      }
    })
  }

  noRightMessage = () => {
    message.error("无访问权限！");
  }

  editShow = (userInfor) => {    // 编辑弹框显示
    this.userInfor = userInfor;  // 点击时对应的用户信息 
    this.setState({
      visible: '2'
    });
  };

  editUserInfor = (userInfor) => {    // 编辑响应函数   vvvvvvvvvvvvvvvvvvvv
    //1.取消对话框
    this.setState({
      visible: '0'
    });
    //2.获取参数，准备数据 
    const user_mobile = this.formRef.current.getFieldValue('user_mobile');
    const user_name = this.formRef.current.getFieldValue('user_name');
    const user_email = this.formRef.current.getFieldValue('user_email');
    const org_id = userInfor.org.org_id;    //this.formRef.current.getFieldValue('org_id');
    const user_remark = this.formRef.current.getFieldValue('user_remark') ? this.formRef.current.getFieldValue('user_remark') : "";
    const roles = this.formRef.current.getFieldValue('user_roles'); 
    const user_roles = []; 
    roles.map((item) => user_roles.push(item))                              
    setTimeout(async() => {
      // console.log('获取的数据',user_mobile,user_name,user_email,user_remark,org_id,user_roles);
      const result = await reqEditUserInfor(user_mobile,user_name,user_email,user_remark,org_id,user_roles);
      // console.log('修改用户信息',result);
      if(result.code === 200){
        message.info(result.data);
        //5.重新显示列表
        this.getUserList();
      }    
    },400);  
  };
  
  handleCancel = () => {     // 对话框取消按钮
    //清除输入的数据
    this.setState({
      visible: '0'
    })
  }

  handleDeleteOnOk = async(userInfor) => {  // 删除onOk      
    const user_mobile = userInfor.user_mobile;
    const org_id = userInfor.org.org_id;
    const result = await reqDeleteUser(user_mobile,org_id);  
    // console.log("删除",result);
    if(result.code === 200){
      message.info(result.data);
      this.getUserList();
    }   
  };

  showDeleteConfirm = (userInfor) => {   // 删除响应函数
    confirm({
      title: '您确定要删除该用户吗?',
      icon: <ExclamationCircleOutlined />,
      okText: '删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => this.handleDeleteOnOk(userInfor)  
    })
 };

  handleLockedOnOk = async(userInfor) => {    //  锁定onOk  
    this.setState({
      visible: '0'
    });
    const user_mobile = userInfor.user_mobile;
    const org_id = userInfor.org.org_id;  
    const user_locked = !userInfor.user_locked;
    const result = await reqLockedConfirm(user_mobile,org_id,user_locked);
    // console.log("锁定解锁",result);
    if(result.code === 200){
      // 重新获取页面
      this.getUserList();
      message.info(result.data)
    } 
  };
  showLockedConfirm = (userInfor) => {    // 锁定解锁 响应函数    
    const {user_locked} = userInfor;
    confirm({
      title: (user_locked)?'您确定要解锁该用户吗?':'您确定要锁定该用户吗?',
      icon: <ExclamationCircleOutlined />,
      okText: (user_locked)?'解锁':'锁定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => this.handleLockedOnOk(userInfor),
    });
  };

  handleEnableOnOk = async(userInfor) => {    //  停用onOk       
    this.setState({
      visible: '0'
    });
    const user_mobile = userInfor.user_mobile;
    const org_id = userInfor.org.org_id;  
    const user_enabled = !userInfor.user_enable;
    const result = await reqEnableConfirm(user_mobile,org_id,user_enabled);
    // console.log("启用停用",result);
    if(result.code === 200){
      message.info(result.data)
      this.getUserList();
    } 
  };
  showEnableConfirm = (userInfor) => {    // 停用启用 响应函数
    const {user_enable} = userInfor;
    confirm({
      title: (user_enable)?'您确定要停用该用户吗?':'您确定要启用该用户吗?',
      icon: <ExclamationCircleOutlined />,
      okText: (user_enable)?'停用':'启用',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => this.handleEnableOnOk(userInfor),
    });
  };

  componentWillMount() {
    this.initColumns();
    this.getOrganList();
    this.getroleButtons();  // 获取有权限的按钮
  }
  componentDidMount() {
    this.getUserList(); 
  }

  render() {
    const {loading,visible,searchType,userList} = this.state;
    const userInfor = this.userInfor || {};
    
    return (
      <div className='user-mgt-wrapper'>
        <div className='user-mgt-header'>
          <Select
            className='user-header-dropdown'  
            style={{ width: 145 }} 
            showSearch
            defaultValue="org_search"
            onChange={(e) => this.handleSearchType(e)}  // 返回选中项的value值 
            dropdownStyle={{
              background:'rgb(7,20,75)',
              border:'1px solid rgb(24 53 142)'
            }}
          >
            <Option style={{color:'rgb(165,173,180)'}} value='org_search' disabled={this.state.roleButtons.indexOf("user-find-organizationId") === -1 ? true : false} >根据矿区查找</Option>
            <Option style={{color:'rgb(165,173,180)'}} value='name_search' disabled={this.state.roleButtons.indexOf("user-find-name") === -1 ? true : false} >根据姓名查找</Option>
            <Option style={{color:'rgb(165,173,180)'}} value='mobile_search' disabled={this.state.roleButtons.indexOf("user-find-mobile") === -1 ? true : false} >根据手机号查找</Option>
          </Select>
          {this.showSearchByType(searchType)}
        </div>
        
        <div className='user-mgt-content'>
          <Table
            columns={this.columns}
            dataSource={userList} 
            size='middle'
            //pagination={{defaultPageSize: 13}}
            className='table_col'
            loading={loading}  
            pagination={false} 
            locale = {{
              cancelSort:'点击取消排序',
              triggerAsc:'点击升序',
              triggerDesc:'点击降序'
            }}  
          />

          <Modal
            title="编辑用户信息"
            visible={visible === '2'}
            onOk={() => this.editUserInfor(userInfor)}
            onCancel={this.handleCancel}
            okText="确定"
            cancelText="取消"
            destroyOnClose={true}
          >
            <EditUserForm 
              userName = {userInfor.user_name}
              userEmail = {userInfor.user_email}
              userRoles = {userInfor.user_roles}   //传过去数组
              userMobile = {userInfor.user_mobile}
              organ = {userInfor.org}
              userRemark = {userInfor.user_remark}
              setUser = {(formRef) => {this.formRef = formRef}}  // 获取 子组件 传递过来的user对象参数
            />
          </Modal>
        </div>
      </div>
    )
  }
}

export default connect(
  state => ({user: state.user, }),
  {}
)(UserMgt);